package com.oocl.jmsbook.util;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

public class JMSUtil {
	
	private static final String MQ_URL = "tcp://127.0.0.1:61616";
	private static final String QUEUE_NAME = "jqueue";

	public static Connection createConnection() {
		Connection conn = null;
		try {
			conn = new ActiveMQConnectionFactory(MQ_URL).createConnection();
		} catch (JMSException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static ActiveMQQueue getQueue() {
		return new ActiveMQQueue(QUEUE_NAME);
	}
	
	public static void close(MessageProducer producer, MessageConsumer consumer, Session sess, Connection conn) {
		if (producer != null) {
			try {
				producer.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
		if (consumer != null) {
			try {
				consumer.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
		if (sess != null) {
			try {
				sess.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
		if (conn != null) {
			try {
				conn.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
}
